package com.demo.study.thread;

import org.junit.jupiter.api.Test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class T06_ReentrantLock {
    @Test
    public void test1() {
        // 可重入锁，+AQS AbstractQueuedSynchronizer
        Lock lock = new ReentrantLock();
        try {
            lock.lock();
            doProcess();
        } finally {
            lock.unlock();
            System.out.println("lock.unlock end...");
        }
    }

    private void doProcess() {
        System.out.println("Thread_Demo1 doProcess ...");
    }

    /**
     * 线程1获取锁成功
     * 线程2获取锁成功
     * 线程2唤醒线程1
     * 线程2释放锁
     * 线程1被唤醒了
     * 线程1释放锁
     */
    @Test
    public void test2() {
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        Thread thread1 = new Thread(() -> {
            try {
                lock.lock();
                System.out.println("线程1获取锁成功");
                try {
                    condition.await(); // 阻塞，释放锁
                    System.out.println("线程1被唤醒了");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } finally {
                lock.unlock();
                System.out.println("线程1释放锁");
            }
        });

        Thread thread2 = new Thread(() -> {
            try {
                lock.lock();
                System.out.println("线程2获取锁成功");
                condition.signal(); // 唤醒阻塞的线程
                System.out.println("线程2唤醒线程1");
            } finally {
                lock.unlock();
                System.out.println("线程2释放锁");
            }
        });

        thread1.start();
        thread2.start();
    }

    @Test
    public void test3() {

    }


}
